/**
 * @description 登录、获取用户信息、退出登录、清除accessToken逻辑，不建议修改
 */

import Vue from 'vue'
import { ActionContext } from 'vuex'
import { State } from "../interface"
import { getUserInfo, login } from '@/api/user'
import {
  getAccessToken,
  removeAccessToken,
  setAccessToken,
} from '@/utils/accessToken'
// import { resetRouter } from '@/router'
import cfg from '@/config'
import { Console } from 'console'
const { tokenName } = cfg
/** 用户vuex数据 */
interface User {
  accessToken: string | null;
  username: string;
  avatar: string;
  permissions: string[];
}

type Action = ActionContext<User, State>

const state = (): User => ({
  accessToken: getAccessToken(),
  username: '123',
  avatar: '',
  permissions: [],
})
const getters = {
  accessToken: (state: User) => state.accessToken,
  username: (state: User) => state.username,
  avatar: (state: User) => state.avatar,
  permissions: (state: User) => state.permissions,
}
const mutations = {
  setAccessToken(state: User, accessToken: string) {
    state.accessToken = accessToken
    setAccessToken(accessToken)
  },
  setUsername(state: User, username: string) {
    state.username = username
  },
  setAvatar(state: User, avatar: string) {
    state.avatar = avatar
  },
  setPermissions(state: User, permissions: string[]) {
    state.permissions = permissions
  },
}
const actions = {
  setPermissions({ commit }: Action, permissions: string[]) {
    commit('setPermissions', permissions)
  },
  async login({ commit }: Action, userInfo: any) {
    const { data } = await login(userInfo) as any
    const accessToken = data[tokenName] as string
    if (accessToken) {
      commit('setAccessToken', accessToken)
      const hour = new Date().getHours()
      const thisTime =
        hour < 8
          ? '早上好'
          : hour <= 11
            ? '上午好'
            : hour <= 13
              ? '中午好'
              : hour < 18
                ? '下午好'
                : '晚上好'
      console.log(`欢迎登录`, `${thisTime}！`)
      return true
      // Vue.prototype.$baseNotify(`欢迎登录${title}`, `${thisTime}！`)
    } else {
      console.log(`登录接口异常，未正确返回${tokenName}...`)
      return false
      // Vue.prototype.$baseMessage(
      //   `登录接口异常，未正确返回${tokenName}...`,
      //   'error'
      // )
    }
  },
  async getUserInfo({ commit, state }: Action) {
    const data = await getUserInfo() as any
    console.log(data)
    if (!data.ok) {
      console.log('验证失败，请重新登录...')
      // Vue.prototype.$baseMessage('验证失败，请重新登录...', 'error')
      return false
    }
    let { permissions, username, avatar } = data.data
    if (permissions && username && Array.isArray(permissions)) {
      commit('setPermissions', permissions)
      commit('setUsername', username)
      commit('setAvatar', avatar)
      return permissions
    } else {
      console.log('用户信息接口异常')
      // Vue.prototype.$baseMessage('用户信息接口异常', 'error')
      return false
    }
  },
  async logout({ dispatch }: Action) {
    // await logout(state.accessToken)
    await dispatch('resetAccessToken')
    // await resetRouter()
  },
  resetAccessToken({ commit }: Action) {
    commit('setPermissions', [])
    commit('setAccessToken', '')
    removeAccessToken()
  },
}
export default { state, getters, mutations, actions }
